<?php

class View_Form {
	
	private $method = 'POST'; 			// Тип передачи данных в форме
	private $id; 						// id элемента 
	private $class; 					// class элемента
	private $leftWidth; 				// Ширина колонки
	private $multipart = false; 				// Ширина колонки
	
	private $objModel; 					// Имя модели
	private $availableSettings = array(
									'class',
									'id',
									'value',
									'name',
									'label',
									'text',
									'autocomplete',
									'wrapClass'
									);
	
	private $arrCurrentSettings = array();
	/**
	 * Задает параметры формы и открывает ее
	 * @param array $arrSettings - массив настроек
	 */
	public function __construct($arrSettings = array(), $objModel = null) {
		if (!empty($arrSettings['method'])) $this->method = $arrSettings['method'];
		if (!empty($arrSettings['id'])) $this->id = $arrSettings['id'];
		if (!empty($arrSettings['class'])) $this->class = $arrSettings['class'];
		if (!empty($arrSettings['left-width'])) $this->leftWidth = $arrSettings['left-width'];
		if (!empty($arrSettings['multipart'])) $this->multipart = true;
		if ($objModel) $this->objModel = $objModel;
	}	
	
	public function show() {
		echo '<form' . ($this->id ? ' id="' . $this->id . '"' : null) . ($this->class ? ' class="' . $this->class . '"' : null) . ($this->method ? ' method="' . $this->method . '"' : null) . ($this->multipart ? 'enctype="multipart/form-data"' : null) . '>';
		if(!empty($this->objModel->arrErrors)) $this->showErrors();
	}
	
	public function close() {
		echo '</form>';
	}
	
	public function showErrors() {
		echo '<div class="val-errors">';
			echo '<div class="err-head">Ошибки:</div>';
			foreach($this->objModel->arrErrors as $error) {
				echo '<div>' . $error . '</div>';
			}
		echo '</div>';
	}
	
	public function showLabel(&$arrSettings) {
		echo '<label for="' . $arrSettings['id'] . '">' . $arrSettings['label'] . '</label>';	
	}
	
	public function textField($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		echo '<div class="field">';
			if(isset($arrSettings['text'])) echo '<div class="field-header" ' . (isset($this->leftWidth) ? 'style="width:' . $this->leftWidth . 'px;"' : '') . '>' . $arrSettings['text'] . '</div>';
			echo '<div class="input-wrap' . (isset($arrSettings['wrapClass']) ? ' ' . $arrSettings['wrapClass'] : '') . '"' . (isset($this->leftWidth) ? ' style="margin-left:' . $this->leftWidth . 'px;"' : '') . '>';
				echo '<input type="text"' . $this->showAttributes() . '>';
				if(isset($arrSettings['label'])) $this->showLabel($arrSettings);
				if(isset($arrSettings['class']) && $arrSettings['class'] == 'city-field') echo '<div><a href="' . W_ABSPATH . 'add_city" class="city-tod s-pod">Нет вашего города?</a></div>';
			echo '</div>';
		echo '</div>';
	}
	
	public function textArea($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		$value = isset($this->arrCurrentSettings['value']) ? $this->arrCurrentSettings['value'] : '';
		unset($this->arrCurrentSettings['value']);

		echo '<div class="field">';
			if(isset($arrSettings['text'])) echo '<div class="field-header" ' . (isset($this->leftWidth) ? 'style="width:' . $this->leftWidth . 'px;"' : '') . '>' . $arrSettings['text'] . '</div>';
			echo '<div class="input-wrap' . (isset($arrSettings['wrapClass']) ? ' ' . $arrSettings['wrapClass'] : '') . '"' . (isset($this->leftWidth) ? ' style="margin-left:' . $this->leftWidth . 'px;"' : '') . '>';
				echo '<textarea ' . $this->showAttributes() . '>' . $value . '</textarea>';
				if(isset($arrSettings['label'])) $this->showLabel($arrSettings);
			echo '</div>';
		echo '</div>';
			
	}
	
	public function password($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		echo '<div class="field">';
			if(isset($arrSettings['text'])) echo '<div class="field-header" ' . (isset($this->leftWidth) ? 'style="width:' . $this->leftWidth . 'px;"' : '') . '>' . $arrSettings['text'] . '</div>';
			echo '<div class="input-wrap"' . (isset($this->leftWidth) ? ' style="margin-left:' . $this->leftWidth . 'px;"' : '') . '>';
				echo '<input type="password"' . $this->showAttributes() . '>';
				if(isset($arrSettings['label'])) $this->showLabel($arrSettings);
			echo '</div>';
		echo '</div>';
	}
	
	public function submit($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		$value = isset($this->arrCurrentSettings['value']) ? $this->arrCurrentSettings['value'] : 'Отправить';
		unset($this->arrCurrentSettings['value']);
		echo '<button type="submit"' . $this->showAttributes() . '>' . $value . '</button>';	
	}
	
	public function hiddenField($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		echo '<input type="hidden"' . $this->showAttributes() . '>';
	}
	/**
	 * Функция для отображения набора полей даты(день, месяц, год)
	 * 
	 * @param string $fieldName - названия поля из БД, в котором будет хранится дата 
	 */
	public function dateFields($fieldName) {
		if($this->objModel->id && $this->objModel->getField($fieldName)) {
			$dateArr = explode('-', $this->objModel->getField($fieldName));
			$this->objModel->setField('day', intval($dateArr[2]));
			$this->objModel->setField('month', $dateArr[1]);
			$this->objModel->setField('year', $dateArr[0]);
		}
		$arrDays = array();
		$arrYears = array();
		
		for($i = 0; $i <= 31; $i++) {
			if ($i == 0) $arrDays[$i] = 'День';
			else $arrDays[$i] = $i;
		}
		
		$arrMonth = array(
			0 => 'Месяц',
			1 => 'Январь', 
			2 => 'Февраль', 
			3 => 'Март', 
			4 => 'Апрель', 
			5 => 'Май', 
			6 => 'Июнь',
			7 => 'Июль',
			8 => 'Август',
			9 => 'Сентябрь',
		 	10 => 'Октябрь',
			11 => 'Ноябрь',
			12 => 'Декабрь'
		);
		
		for($i = 2013; $i >= 1920; $i--) {
			if ($i == 2013) $arrYears[0] = 'Год';
			else $arrYears[$i] = $i;
		}
		$this->select(array('name' => 'day', 'class' => 'date-day', 'options' => $arrDays));
		$this->select(array('name' => 'month', 'class' => 'date-month', 'options' => $arrMonth));
		$this->select(array('name' => 'year', 'class' => 'date-year', 'options' => $arrYears));
	}
	
	private function setAttributes($arrSettings = array()) {
		/* foreach ($arrSettings as $settingKey => $settingValue) {
			if ($settingKey == 'name' && $this->objModel) {
				$modelName = get_class($this->objModel); // Получаем имя модели
				$setting .= ' name="' . $modelName . '[' . $settingValue . ']"';
			}
			elseif ($settingKey != 'value') $setting .= ' ' . $settingKey . '="' . $settingValue . '"';						
		}
		if (isset($arrSettings['name']) && $arrSettings['name'] != 'password' && $this->objModel && $this->objModel->getField($arrSettings['name'])) $setting .= ' value="' . $this->objModel->getField($arrSettings['name']) . '"';
		elseif (isset($arrSettings['value'])) $setting .= ' value="' . $arrSettings['value'] . '"';
		*/
		$this->arrCurrentSettings = array();
		foreach ($arrSettings as $settingKey => $settingValue) {
			if(in_array($settingKey, $this->availableSettings)) {
				if ($settingKey == 'name' && $this->objModel) {
					$modelName = get_class($this->objModel); // Получаем имя модели
					$this->arrCurrentSettings['name'] = $modelName . '[' . $settingValue . ']';
				}
				elseif ($settingKey != 'value') $this->arrCurrentSettings[$settingKey] = $settingValue;
			}
		}
		// Пытаемся получить значение из объекта
		if (!isset($arrSettings['noFromModel']) && isset($arrSettings['name']) && $arrSettings['name'] != 'password' && $this->objModel) {
			$this->arrCurrentSettings['value'] = $this->objModel->getField($arrSettings['name']);
		}
		elseif (isset($arrSettings['value'])) $this->arrCurrentSettings['value'] = $arrSettings['value'];
	}
	
	public function showAttributes() {
		if (!empty($this->arrCurrentSettings)) {
			$setting = '';
			foreach ($this->arrCurrentSettings as $attrName => $attrValue) {
				if($attrName != 'label' && $attrName != 'wrapClass') $setting .= ' ' . $attrName  . '="' . $attrValue . '"';
			}
			return $setting;
		}
	}
	
	public function select($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		$checkedValue = null;
		if ($this->objModel && $this->objModel->getField($arrSettings['name']) !== null) $checkedValue = $this->objModel->getField($arrSettings['name']);
		elseif (isset($this->arrCurrentSettings['value'])) $checkedValue = $this->arrCurrentSettings['value'];
		unset($this->arrCurrentSettings['value']);
		
		echo '<div class="field">';
			if(isset($arrSettings['text'])) echo '<div class="field-header" ' . (isset($this->leftWidth) ? 'style="width:' . $this->leftWidth . 'px;"' : '') . '>' . $arrSettings['text'] . '</div>';
			echo '<div class="sel' . (isset($arrSettings['wrapClass']) ? ' ' . $arrSettings['wrapClass'] : '') . '"' . (isset($this->leftWidth) ? ' style="margin-left:' . $this->leftWidth . 'px;"' : '') . '>';
				echo '<select' . $this->showAttributes() . '>';
				if(isset($arrSettings['chooseText'])) echo '<option value=""' . ($checkedValue  === null ? ' selected="selected"' : '') . '>' . $arrSettings['chooseText'] . '</option>';
				$optionsArray = isset($arrSettings['options']) ? $arrSettings['options'] : null;
					if($optionsArray) {
						foreach ($optionsArray as $value => $stringValue) {
							echo '<option value="' . $value . '"'  . (isset($checkedValue) && $checkedValue == $value && $checkedValue != null ? ' selected="selected"' : '') . '>' . $stringValue . '</option>';
						}
					}
				echo '</select>';
			echo '</div>';
		echo '</div>';
	}
	
	public function radio($arrSettings = array()) {
		$arrSettings['noFromModel'] = true;
		$this->setAttributes($arrSettings);
		
		echo '<div class="field">';	
			echo '<div class="input-wrap rad">';
				echo '<input type="radio"' . $this->showAttributes() . (isset($arrSettings['is_checked']) && $arrSettings['is_checked'] ? ' checked="checked"' : '') . ' value="' . (isset($arrSettings['value']) && $arrSettings['value'] ? : '') . '">';
				if(isset($arrSettings['label'])) echo '<label for="' . $arrSettings['id'] . '" class="radio-label">' . $arrSettings['label'] . '</label>';
			echo '</div>';
		echo '</div>';
	}
	
	public function checkbox($arrSettings = array()) {
		$this->setAttributes($arrSettings);
		echo '<div class="input-wrap' . (isset($arrSettings['wrapClass']) ? ' ' . $arrSettings['wrapClass'] : '') . '">';
			echo '<input type="checkbox"' . $this->showAttributes() . (isset($arrSettings['is_checked']) && $arrSettings['is_checked'] ? ' checked="checked"' : '') . '>';
			if(isset($arrSettings['label'])) echo '<label for="' . $arrSettings['id'] . '" class="radio-label">' . $arrSettings['label'] . '</label>';
		echo '</div>';
	}
}

?>